package com.sunday.fangdaifu.activity.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flyco.tablayout.SlidingTabLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sunday.common.adapter.MainFragmentPagerAdapter;
import com.sunday.common.base.BaseApplication;
import com.sunday.common.base.BaseFragment;
import com.sunday.common.model.ResultDO;
import com.sunday.common.qrcode.CaptureActivity;
import com.sunday.common.utils.PixUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.fangdaifu.R;
import com.sunday.fangdaifu.activity.task.TaskDetailActivity;
import com.sunday.fangdaifu.activity.task.TaskListFragment;
import com.sunday.fangdaifu.adapter.CardViewAdapter;
import com.sunday.fangdaifu.base.MyApplication;
import com.sunday.fangdaifu.common.Api;
import com.sunday.fangdaifu.common.ApiClient;
import com.sunday.fangdaifu.common.ApiServiceImpl;
import com.sunday.fangdaifu.model.DateBanner;
import com.sunday.fangdaifu.model.Task;
import com.sunday.fangdaifu.model.TaskCount;
import com.sunday.fangdaifu.widgets.VpSwipeRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


import static android.app.Activity.RESULT_OK;


/**
 * Created by yun_sheng on 2017/6/29.
 */

public class TaskFragment extends BaseFragment implements ApiServiceImpl.HttpResponseInterface {


    @Bind(R.id.right)
    ImageView right;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.title_bar)
    RelativeLayout titleBar;
    @Bind(R.id.img_view_pager)
    ViewPager imgViewPager;
    @Bind(R.id.slide_tab)
    SlidingTabLayout slideTab;
    @Bind(R.id.view_pager)
    ViewPager viewPager;
    @Bind(R.id.swipe_refresh_layout)
    VpSwipeRefreshLayout refreshLayout;
    @Bind(R.id.floating_button)
    FloatingActionButton floatingActionButton;
    @Bind(R.id.appbar_layout)
    AppBarLayout appBarLayout;

    private int userId;
    static int TASK_TYPE_NORMAL = 1;//正常巡检
    static int TASK_TYPE_SPECIAL = 2;//分配巡检
    static int TASK_TYPE_FEEDBACK = 3;//居民反馈


    public static TaskFragment newInstance() {
        TaskFragment fragment = new TaskFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_task1, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }


    private CardViewAdapter adapter;
    private List<TaskCount> taskCounts = new ArrayList<>();

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        userId = MyApplication.getInstance().getMember().getId();
        getTaskCount();
        initSwipRefresh();
        initImgViewPager();
        initTaskViewPager();

    }

    private void initSwipRefresh() {
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset >= 0) {
                    refreshLayout.setEnabled(true);
                } else refreshLayout.setEnabled(false);
            }
        });
        refreshLayout.setColorSchemeResources(R.color.material_red, R.color.material_green,
                R.color.material_blue, R.color.material_yellow);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initImgViewPager();
                getTaskCount();
            }
        });

    }

    private void getTaskCount() {
        ApiClient.getApiService().taskCount(userId, this, new TypeToken<ResultDO<List<TaskCount>>>() {
        }.getType());
    }

    private int pos=1;
    private void initImgViewPager() {
        adapter = new CardViewAdapter(mContext);
        imgViewPager.setClipToPadding(false);
        imgViewPager.setAdapter(adapter);
        imgViewPager.setPageTransformer(true, new ScalePageTransformer());
        imgViewPager.setPadding(PixUtils.dip2px(mContext, 40), 0, PixUtils.dip2px(mContext, 40), 0);
        // imgViewPager.setPadding( PixUtils.dip2px(mContext,40),0, PixUtils.dip2px(mContext,40),0);
        imgViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {


                                                 @Override
                                                 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                                                 }

                                                 @Override
                                                 public void onPageSelected(int position) {
                /*if (position == adapter.getCount() - 1) {
                    imgViewPager.setPadding(PixUtils.dip2px(mContext, 40), 0, 0, 0);
                } else if (position == 0) {
                    imgViewPager.setPadding(0, 0, PixUtils.dip2px(mContext, 40), 0);
                } else {
                    imgViewPager.setPadding(PixUtils.dip2px(mContext, 40), 0, PixUtils.dip2px(mContext, 40), 0);
                }*/                                           pos=position;
                                                     TaskCount taskCount = taskCounts.get(position);
                                                     if (taskCount.getType() == TASK_TYPE_NORMAL) {
                                                         slideTab.getTitleView(0).setText("待巡检");
                                                         slideTab.getTitleView(1).setText("已完成");
                                                         floatingActionButton.setVisibility(View.VISIBLE);
                                                     } else if (taskCount.getType() == TASK_TYPE_SPECIAL) {
                                                         slideTab.getTitleView(0).setText("待执行");
                                                         slideTab.getTitleView(1).setText("已完成");
                                                         floatingActionButton.setVisibility(View.VISIBLE);
                                                     } else {
                                                         slideTab.getTitleView(0).setText("未处理");
                                                         slideTab.getTitleView(1).setText("已处理");
                                                         floatingActionButton.setVisibility(View.GONE);
                                                     }
                                                     ((TaskListFragment) fragments.get(0)).setType(taskCount.getType());
                                                     ((TaskListFragment) fragments.get(0)).updateData();

                                                     ((TaskListFragment) fragments.get(1)).setType(taskCount.getType());
                                                     ((TaskListFragment) fragments.get(1)).updateData();
                                                 }

                                                 @Override
                                                 public void onPageScrollStateChanged(int state) {
                                                 }


                                             }
        );

    }



    @OnClick(R.id.floating_button)
    void scan() {
        Intent intent = new Intent(getActivity(), CaptureActivity.class);
        startActivityForResult(intent, 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        Gson gson = new Gson();
        String result = data.getStringExtra("result");
        if (!TextUtils.isEmpty(result) && result.length() > 4) {
            String id = result. substring(result.lastIndexOf('/') + 1,result.length());
            ApiClient.getApiService().taskId(userId, Integer.valueOf(id), this, new TypeToken<ResultDO<Integer>>() {
            }.getType());
        }

    }

    private ArrayList<Fragment> fragments = new ArrayList<>();
    private List<String> titles = new ArrayList<>();

    private void initTaskViewPager() {
        titles.add("待巡检");
        titles.add("已完成");
        fragments.add(TaskListFragment.newInstance(TASK_TYPE_NORMAL, 0));
        fragments.add(TaskListFragment.newInstance(TASK_TYPE_NORMAL, 1));
        viewPager.setAdapter(new MainFragmentPagerAdapter(getChildFragmentManager(), fragments,
                titles));
        slideTab.setViewPager(viewPager);
        viewPager.setCurrentItem(0, false);

    }

    private class ScalePageTransformer implements ViewPager.PageTransformer {

        static final float MAX_SCALE = 1.0f;
        static final float MIN_SCALE = 0.9f;

        @Override
        public void transformPage(View page, float position) {

            if (position < -1) {
                position = -1;
            } else if (position > 1) {
                position = 1;
            }

            float tempScale = position < 0 ? 1 + position : 1 - position;

            float slope = (MAX_SCALE - MIN_SCALE) / 1;
            //一个公式
            float scaleValue = MIN_SCALE + tempScale * slope;
            page.setScaleX(scaleValue);
            page.setScaleY(scaleValue);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onResponce(String key, Object result) {
        if (isFinish) {
            return;
        }
        switch (key) {
            case Api.TASK_COUNT:
                refreshLayout.setRefreshing(false);
                ResultDO<List<TaskCount>> resultDO = (ResultDO<List<TaskCount>>) result;
                if (resultDO.getCode() == 0)
                    taskCounts.clear();
                taskCounts.addAll(resultDO.getResult());
                adapter.setData(taskCounts);
                adapter.notifyDataSetChanged();
                if (!taskCounts.isEmpty() && taskCounts.size() > 1)
                    imgViewPager.setCurrentItem(pos);
                break;
            case Api.TASK_ID:
                ResultDO<Integer> resultDO2 = (ResultDO<Integer>) result;
                if (resultDO2.getCode() == 0) {
                    Intent intent = new Intent(mContext, TaskDetailActivity.class);
                    intent.putExtra("id", resultDO2.getResult());
                    startActivity(intent);
                } else {
                    ToastUtils.showToast(mContext, resultDO2.getMessage());
                }
                break;
        }
    }

    @Override
    public void onFailure() {
        refreshLayout.setRefreshing(false);
        ToastUtils.showToast(mContext, "网络连接错误");
    }
}
